﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word=Microsoft.Office.Interop.Word;
using MSOffice = Microsoft.Office.Core;

namespace MyWordAddIn
{
    /// <summary>
    /// 文档的样式：包括项目编号，字体，颜色，对齐
    /// </summary>
    public class WordXMLParts
    {
        Word.Document doc;
        public WordXMLParts(Word.Document doc)
        {
            this.doc = doc;
        }

        public void GetXMLParts(Message msg,string ns)
        {
            MSOffice.CustomXMLParts parts = doc.CustomXMLParts.SelectByNamespace(ns);
            if (parts.Count == 1)
            {
                MSOffice.CustomXMLNodes personNode = parts[1].DocumentElement.SelectNodes("ns0:person");
                //bugInfoListNode.SelectNodes("ns0:buginfo") 再选择子节点
                foreach (MSOffice.CustomXMLNode node in personNode)
                {
                    string name = node.SelectSingleNode("ns0:name").Text.Trim();
                    string age = node.SelectSingleNode("ns0:age").Text.Trim();
                    msg.AddMsg("Name", name);
                    msg.AddMsg("Age", age);
                }
            }
        }

        public void SetXMLParts(Message msg,string ns)
        {
            MSOffice.CustomXMLParts parts = doc.CustomXMLParts.SelectByNamespace(ns);
            //没有信息的话创建                
            if (parts.Count == 0)
            {
                string xml ="<personList xmlns=\"" + ns + "\">" 
                            + "<person>"
                            + "<name>Jack</name><age>20</age>"
                            + "</person>"
                            + "<person>"
                            + "<name>Sue</name><age>16</age>"
                            + "</person>"
                            + "</personList>";

                object missing = System.Reflection.Missing.Value;
                doc.CustomXMLParts.Add(xml, missing);
                doc.Save();
                msg.AddMsg("XMLParts", xml);
            }
        }

        public void DelXMLParts(string ns)
        {
            MSOffice.CustomXMLParts parts = doc.CustomXMLParts.SelectByNamespace(ns);
            if (parts.Count == 1)
            {
                parts[1].Delete();
                doc.Save();
            }
        }

    }
}
